using B.S.NewMedical.Api.Write.Application.Command.Order.Medicine;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Order.Medicine
{
    /// <summary>
    /// 批量删除药品处理器
    /// </summary>
    public class BatchDeleteMedicineCommandHandle : IRequestHandler<BatchDeleteMedicineCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MedicineModel> _medicineRepository;
        private readonly ILogger<BatchDeleteMedicineCommandHandle> _logger;

        public BatchDeleteMedicineCommandHandle(
            IBaseRepository<MedicineModel> medicineRepository,
            ILogger<BatchDeleteMedicineCommandHandle> logger)
        {
            _medicineRepository = medicineRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(BatchDeleteMedicineCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                _logger.LogInformation("开始批量删除药品记录，数量：{Count}", request.MedicineIds.Count);

                // 1. 查找要删除的药品记录
                var medicines = _medicineRepository.GetAll()
                    .Where(x => request.MedicineIds.Contains(x.Id) && !x.IsDeleted)
                    .ToList();

                if (medicines == null || medicines.Count == 0)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "未找到要删除的药品记录";
                    _logger.LogWarning("未找到要删除的药品记录，IDs：{Ids}", 
                        string.Join(",", request.MedicineIds));
                    return result;
                }

                // 2. 检查是否有已完成的药品订单
                var completedMedicines = medicines
                    .Where(x => !string.IsNullOrEmpty(x.Orderstatus) && 
                               x.Orderstatus.Equals("已完成", StringComparison.OrdinalIgnoreCase))
                    .ToList();

                if (completedMedicines.Any())
                {
                    var completedIds = string.Join(",", completedMedicines.Select(x => x.Id));
                    result.Code = ApiEnum.Fail;
                    result.Msg = $"以下药品订单已完成，不能删除：{completedIds}";
                    _logger.LogWarning("尝试删除已完成的药品订单，IDs：{Ids}", completedIds);
                    return result;
                }

                // 3. 检查是否有已发货的药品订单
                var shippedMedicines = medicines
                    .Where(x => !string.IsNullOrEmpty(x.Orderstatus) && 
                               x.Orderstatus.Equals("已发货", StringComparison.OrdinalIgnoreCase))
                    .ToList();

                if (shippedMedicines.Any())
                {
                    var shippedIds = string.Join(",", shippedMedicines.Select(x => x.Id));
                    result.Code = ApiEnum.Fail;
                    result.Msg = $"以下药品订单已发货，不能删除：{shippedIds}";
                    _logger.LogWarning("尝试删除已发货的药品订单，IDs：{Ids}", shippedIds);
                    return result;
                }

                // 4. 执行批量逻辑删除
                var currentTime = DateTime.Now;
                foreach (var medicine in medicines)
                {
                    medicine.IsDeleted = true;
                    medicine.UpdateTime = currentTime;
                }

                // 5. 批量更新数据库
                var updateResult = await _medicineRepository.UpdateRangAsync(medicines);

                if (updateResult > 0)
                {
                    result.Code = ApiEnum.Success;
                    result.Msg = $"成功删除 {updateResult} 条药品记录";
                    result.Data = updateResult;
                    
                    _logger.LogInformation("批量删除药品记录成功，数量：{Count}，IDs：{Ids}", 
                        updateResult, string.Join(",", request.MedicineIds));
                }
                else
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "批量删除药品记录失败";
                    result.Data = updateResult;
                    
                    _logger.LogError("批量删除药品记录失败，IDs：{Ids}", 
                        string.Join(",", request.MedicineIds));
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"批量删除药品记录时发生异常：{ex.Message}";
                
                _logger.LogError(ex, "批量删除药品记录时发生异常，IDs：{Ids}，异常信息：{Message}", 
                    string.Join(",", request.MedicineIds), ex.Message);
            }

            return result;
        }
    }
} 